/**
 * 剖析comparable and comparator
 */
package demo3;

import java.util.Arrays;
import java.util.Comparator;

class Student implements Comparable<Student> {
    public String name;
    public int age;
    public Student(String name,int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Student o) {
        //return this.age - o.age;
        return this.name.compareTo(o.name);//重写compareTo方法,调用String重写的compareTo方法
    }
}
class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}
class NameComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}
public class Test {
    /**
     * comparator(一般称为比较器)
     * @param args
     *      1.实现Comparator接口
     *      2.重写compareTo方法
     * 优点:灵活(游离于类之外,需要通过什么比较,就创建一个类实现该接口,并重写方法即可)
     */
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("zhangSan",19);
        students[1] = new Student("liSi",51);
        students[2] = new Student("wangWu",34);

        NameComparator nameComparator = new NameComparator();
        Arrays.sort(students,nameComparator);//给sort传递了一个比较方法

        System.out.println(Arrays.toString(students));
    }
    public static void main3(String[] args) {
        Student student1 = new Student("zhangSan",16);
        Student student2 = new Student("lisi",30);

        AgeComparator ageComparator = new AgeComparator();
        System.out.println(ageComparator.compare(student1,student2));

        NameComparator nameComparator = new NameComparator();
        System.out.println(nameComparator.compare(student1,student2));
    }
    /**
     * comparable
     * @param args
     *      1.实现Comparable
     *      2.重写compareTo方法
     * 一般情况下,重写后的比较方法就不会再改变(即默认方法)
     * 缺点:不灵活(一般不能进行改变)
     */
    public static void main2(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("zhangSan",19);
        students[1] = new Student("liSi",51);
        students[2] = new Student("wangWu",34);

        Arrays.sort(students);//给sort传递了一个比较方法

        System.out.println(Arrays.toString(students));
    }
    public static void main1(String[] args) {
        Student student1 = new Student("zhangSan",16);
        Student student2 = new Student("lisi",30);

        if(student2.compareTo(student1) > 0) {
            System.out.println("student2 > student1");
        }else {
            System.out.println("student2 < student1");
        }
    }
}
